package com.huayun.weexutil;

import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.text.TextUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.GlideBitmapDrawable;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.huayun.util.utils.LogUtil;
import com.taobao.weex.WXEnvironment;
import com.taobao.weex.WXSDKManager;
import com.taobao.weex.adapter.IWXImgLoaderAdapter;
import com.taobao.weex.common.WXImageStrategy;
import com.taobao.weex.dom.WXImageQuality;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

import com.huayun.util.utils.DownLoadUtil;
import com.huayun.util.utils.FileUtil;
import com.huayun.util.inter_face.Action;
import com.huayun.viewutils.imageutil.glide.GlideCircleTransform;


/**
 * 图片加载器
 */

public class ImageAdapter implements IWXImgLoaderAdapter {
    private boolean isSharpen;


    @Override
    @SuppressWarnings("unchecked")
    public void setImage(final String url, final ImageView view, WXImageQuality quality, final WXImageStrategy strategy) {
        WXSDKManager.getInstance().postOnUiThread(new Runnable() {

            @Override
            public void run() {
                if (view == null || view.getLayoutParams() == null) {
                    return;
                }
                if (TextUtils.isEmpty(url)) {
                    view.setImageBitmap(null);
                    return;
                }
                //LogUtil.e("url----->" + url);
                //处理加载assets目录下图片
                String temp = url;
                temp = getPath(temp, true);
                //LogUtil.e("temp----->" + temp);
                final String loadUrl = temp;
                //处理加载assets目录下图片
                int w = view.getLayoutParams().width;
                int h = view.getLayoutParams().height;

                if (w <= 0 || h <= 0) {
                    return;
                }
                WeakReference<ImageView> weakReference = new WeakReference<ImageView>(view);
                final ImageView weakImg = weakReference.get();
                if (weakImg == null) {
                    return;
                }
                String placeHolder = strategy.placeHolder;
                if (TextUtils.isEmpty(placeHolder)) {
                    Glide.with(WXEnvironment.getApplication()).load(loadUrl).dontAnimate().placeholder(R.drawable.pre_load).error(R.drawable.pre_load).listener(new MyRequestListener(weakImg, url, strategy)).diskCacheStrategy(DiskCacheStrategy.ALL).into(weakImg);

                } else {
                    isSharpen = placeHolder.contains("round_image");
                    if (isAsset(placeHolder)) {
                        placeHolder = getPath(placeHolder, false);
                        Drawable drawable = FileUtil.loadImageFromAsserts(placeHolder);
                        showDiff(drawable, loadUrl, weakImg, url, strategy);
                    } else {
                        DownLoadUtil downLoadUtil = new DownLoadUtil();
                        downLoadUtil.downLoad(placeHolder, new Action<String>() {
                            @Override
                            public void call(String s) {
                                Drawable drawable = Drawable.createFromPath(s);
                                showDiff(drawable, loadUrl, weakImg, url, strategy);
                            }
                        });
                    }

                }
            }
        }, 0);
    }

    @SuppressWarnings("unchecked")
    private void showDiff(Drawable drawable, String loadUrl, ImageView weakImg, String url, WXImageStrategy strategy) {
        if (drawable != null) {
            if (isSharpen) {
                Glide.with(WXEnvironment.getApplication()).load(loadUrl).dontAnimate().skipMemoryCache(true).transform(new GlideCircleTransform(WXEnvironment.getApplication())).placeholder(drawable).error(drawable).diskCacheStrategy(DiskCacheStrategy.ALL).into(weakImg);
            } else {
                Glide.with(WXEnvironment.getApplication()).load(loadUrl).dontAnimate().skipMemoryCache(true).placeholder(drawable).error(drawable).diskCacheStrategy(DiskCacheStrategy.ALL).into(weakImg);
            }
        } else {
            if (isSharpen) {
                Glide.with(WXEnvironment.getApplication()).load(loadUrl).dontAnimate().skipMemoryCache(true).transform(new GlideCircleTransform(WXEnvironment.getApplication())).placeholder(R.drawable.pre_load).error(R.drawable.pre_load).listener(new MyRequestListener(weakImg, url, strategy)).diskCacheStrategy(DiskCacheStrategy.ALL).into(weakImg);
            } else {
                Glide.with(WXEnvironment.getApplication()).load(loadUrl).dontAnimate().skipMemoryCache(true).placeholder(R.drawable.pre_load).error(R.drawable.pre_load).listener(new MyRequestListener(weakImg, url, strategy)).diskCacheStrategy(DiskCacheStrategy.ALL).dontTransform().into(weakImg);
            }
        }
    }

    private String getPath(String temp, boolean modify) {
        Uri parse = Uri.parse(temp);
        return temp;
    }

    private boolean isAsset(String path) {
        Uri parse = Uri.parse(path);
        return parse != null && TextUtils.equals(parse.getScheme(), "file");
    }

    class MyRequestListener implements RequestListener {

        private ImageView imageView;
        private String url;
        private WXImageStrategy strategy;

        public MyRequestListener(ImageView imageView, String url, WXImageStrategy strategy) {
            this.imageView = imageView;
            this.url = url;
            this.strategy = strategy;
        }

        @Override
        public boolean onException(Exception e, Object o, Target target, boolean b) {
            if (strategy.getImageListener() != null) {
                strategy.getImageListener().onImageFinish(url, imageView, false, null);
            }
            imageView.setBackgroundColor(Color.parseColor("#c3c3c3"));
            imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
            return false;
        }

        @Override
        public boolean onResourceReady(Object o, Object o2, Target target, boolean b, boolean b1) {
            if (strategy.getImageListener() != null) {
                //返回图片的宽高
                Map<String, Integer> extra = null;
                if (o instanceof GlideBitmapDrawable) {
                    GlideBitmapDrawable drawable = (GlideBitmapDrawable) o;
                    extra = new HashMap<>();
                    extra.put("naturalWidth", drawable.getIntrinsicWidth());
                    extra.put("naturalHeight", drawable.getIntrinsicHeight());
                }
                strategy.getImageListener().onImageFinish(url, imageView, true, extra);
            }
            return false;
        }

    }

    private String assembleFilePath(Uri uri) {
        if (uri != null && uri.getPath() != null) {
            return uri.getPath().replaceFirst("/", "");
        }
        return "";
    }

}
